package com.yupi.springbootinit.manager;

import cn.hutool.core.util.IdUtil;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;

/**
 * @version 1.0
 * @Author HJY_Maker
 * @Date 2024/6/22 星期六 8:51
 */
@Component
public class UploadToOss {
    @Value("${oss.qiniuyu.accessKey}")
    private String accessKey;
    @Value("${oss.qiniuyu.secretKey}")
    private String secretKey;
    @Value("${oss.qiniuyu.bucket}")
    private String bucket;
    public String uploadToOss(MultipartFile multipartFile){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);

        LocalDate now = LocalDate.now();
        //获取年
        int year = now.getYear();
        //获取年
        int month = now.getMonthValue();
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        StringBuilder fileName = new StringBuilder();
        fileName.append(year);
        fileName.append("/");
        fileName.append(month);
        fileName.append("/");
        fileName.append(IdUtil.simpleUUID());
        fileName.append(multipartFile.getOriginalFilename());

        String key = fileName.toString();
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            InputStream inputStream = multipartFile.getInputStream();
            Response response = uploadManager.put(inputStream, key, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            ex.printStackTrace();
            if (ex.response != null) {
                System.err.println(ex.response);
                try {
                    String body = ex.response.toString();
                    System.err.println(body);
                } catch (Exception ignored) {
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        StringBuilder returnFileName = new StringBuilder();
        returnFileName.append("http://sffepli7g.hn-bkt.clouddn.com/");
        returnFileName.append(fileName);
        return returnFileName.toString();
    }

}
